const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const axios = require('axios');
const fs = require('fs');
var FormData = require('form-data');
class ImageController extends Controller {
  async NewImage() {
    const { ctx } = this;
    const { prompt } = ctx.request.body;
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;

    // const timestamp = Date.now();
    // let content = [{
    //   type: 0,
    //   text,
    //   timestamp
    // }];

    try {
      const randomSeed = Math.floor(Math.random() * 1000000); // 生成0 - 999999的随机数
      // const imageUrl = `https://pollinations.ai/p/${encodeURIComponent(prompt)}?seed=${randomSeed}`;
      let imageUrl = `https://api.pearktrue.cn/api/stablediffusion/?prompt=${prompt}&model=normal`;
      const response = await axios(imageUrl);
      imageUrl = response.data.imgurl;


      // content.push({
      //   type: 1,
      //   text: imageUrl,
      //   timestamp: Date.now()
      // })
      // const result = await ctx.model.Chat.create({ title, content, date: timestamp, userId: res._id, type: 1 });


      const newImage = await ctx.model.Image.create({ prompt, url: imageUrl, userId, favrite: 0, date: Date.now() });

      ctx.body = { success: true, data: newImage };
    }
    catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  async getImageList() {
    const { ctx } = this;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;
    try {
      const images = await ctx.model.Image.find({ userId }).sort({ date: -1 });
      ctx.body = { success: true, data: images };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // 导出时确保包含新的方法
  async getAllImages() {
    const { ctx } = this;
    try {
      const images = await ctx.model.Image.find({}).sort({ date: -1 });
      ctx.body = { success: true, data: images };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async getCollectedImages() {
    const { ctx } = this;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;
    try {
      const collectedImages = await ctx.model.ImageCollect.find({ userId }).sort({ date: -1 });
      ctx.body = { success: true, data: collectedImages };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async addToCollection() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;
    const image = await ctx.model.Image.findById(id).select('userId url prompt');
    try {
      const newCollection = await ctx.model.ImageCollect.create({
        imageId: id,
        userId,
        url: image.url,
        authorId: image.userId,
        date: Date.now(),
        prompt: image.prompt,
      });
      // 更新Favorite字段计数
      await ctx.model.Image.findByIdAndUpdate(id, { $inc: { favrite: 1 } });
      ctx.body = { success: true, data: newCollection };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  async deleteCollection() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;
    try {
      await ctx.model.ImageCollect.deleteOne({ _id: id, userId });
      ctx.body = { success: true, message: '收藏删除成功' };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async NewAudio() {
    const { ctx } = this;
    const { text } = ctx.request.body;
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;

    try {
      const voice = "nova"; // Optional voice parameter
      const url = "https://text.pollinations.ai/" + encodeURIComponent(text) + "?model=openai-audio&voice=" + voice;


      const newImage = await ctx.model.Image.create({ prompt, url: url, userId, date: Date.now() });

      ctx.body = { success: true, data: newImage };
    }
    catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async uploadImage() {
    const { ctx } = this;
    // let stream = await ctx.getFileStream();
    let file = ctx.request.files[0]
    console.log('===========', ctx.request.files[0]);
    try {
      // 这里可以添加文件存储逻辑，例如将文件保存到服务器或云存储
      const formData = new FormData();
      formData.append('source', fs.createReadStream(file.filepath));
      var config = {
        method: 'post',
        url: 'https://www.picgo.net/api/1/upload',
        headers: {
          'X-API-Key': 'chv_SWSCw_6becb1e61a1252d5e9adcdd8711d49574fa9465d78ff890460179f45037e6abbf4362444793e79520d36df0389e0d98c42603fcc61033585c6ca684941c50004',
          'Content-Type': 'multipart/form-data'
        },
        data: formData
      };
      const res = await axios(config)

      console.log('=================', res.data.image.url);
      const res1 = await axios.post('https://api.pearktrue.cn/api/airecognizeimg/', {
        file: res.data.image.url
      })

      // 获取当前用户id
      const token = this.ctx.cookies.get("token", {
        signed: false,
        encrypt: true
      });
      const decoded = jwt.verify(token, "aaa");

      const RecognitionModel = this.ctx.model.Recognition;
      await RecognitionModel.create({
        userId: decoded.id,
        date: Date.now(),
        image: res.data.image.url,
        text: res1.data.result || '',
        like: 0
      });

      ctx.body = {
        success: true, message: '文件识别成功', data: {
          image: res.data.image.url,
          text: res1.data.result
        }
      };
    } catch (error) {
      // console.log('=================111', error)
      ctx.body = { success: false, error: error.message };
    }
  }

  async getMyRecognitionImages() {
    const { ctx } = this;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const userId = decoded.id;
    try {
      const RecognitionModel = ctx.model.Recognition;
      const images = await RecognitionModel.find({ userId }).sort({ date: -1 });
      ctx.body = { success: true, data: images };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
}



module.exports = ImageController;